import { ref } from 'vue'
import type { ContentItem } from '@/models'
import { orderBy } from 'lodash-es'

export const contentData = ref<ContentItem[]>([])

export async function loadContentIndex() {
  try {
    const response = await fetch('./contents/index.json')
    contentData.value = sortEntries(await response.json())
  } catch (error) {
    console.error('Failed to load content data:', error)
    contentData.value = [] // 重置为空的数组
  }
}

export async function fetchContent(path: string): Promise<string> {
  try {
    const response = await fetch(`./contents/${path.replace('md', 'html')}`)
    return await response.text()
  } catch (error) {
    console.error('Failed to fetch content:', error)
    return ''
  }
}

const sortEntries = (contents: any[]) => {
  return orderBy(contents, ['date'], ['desc'])
}
